package club.janna.jrpc.cluster.loadbalance;

import club.janna.jrpc.annotation.SPIService;
import club.janna.jrpc.cluster.loadbalance.selector.GenericRoundSelector;
import club.janna.jrpc.cluster.loadbalance.selector.PowerOfTwoRoundSelector;
import club.janna.jrpc.cluster.loadbalance.selector.Selector;
import club.janna.jrpc.cluster.loadbalance.selector.SingleSelector;
import club.janna.jrpc.rpc.Invoker;

/**
 * 轮询负载均衡器
 * @author Panbo.Guo
 */
@SPIService("round")
public class RoundLoadBalancer extends AbstractLoadBalancer {

    @Override
    protected Selector buildSelector(Invoker[] invokers) {
        int n = invokers.length;
        return n == 1 ? new SingleSelector() : isPowerOfTwo(n) ? new PowerOfTwoRoundSelector(n) : new GenericRoundSelector(n);
    }

    /**
     * 判断是否是2的幂
     * @param n
     * @return
     */
    private boolean isPowerOfTwo(int n) {
        return (n & -n) == n;
    }
}
